package com.tingyuge.base.jdk.io.nio.filelock;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/12
 * @description
 */
public class FileLockDemo1 {

    public static void main(String[] args) throws Exception {
        String input = "input";
        System.out.println(input);
        ByteBuffer buffer = ByteBuffer.wrap(input.getBytes());

        String filePath = "D:/nio/01.txt";
        Path path = Paths.get(filePath);
        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.APPEND);

//        fileChannel.position(fileChannel.size() - 1);
        //加锁
//        FileLock lock = fileChannel.lock();
        FileLock lock = fileChannel.lock(0,Integer.MAX_VALUE,true);
        System.out.println("是否是共享锁: "+ lock.isShared());

        fileChannel.write(buffer);
        fileChannel.close();

        //读文件

        readFile(filePath);
    }

    private static void readFile(String filePath) throws Exception {
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line = bufferedReader.readLine();
        while (line !=null){
            System.out.println(" "+ line);
            line = bufferedReader.readLine();
        }
        fileReader.close();
        bufferedReader.close();
    }


}
